<?php

class QvobjectsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','printObject'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','loadObjects'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Qvobjects;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qvobjects']))
		{
			$model->attributes=$_POST['Qvobjects'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->qvo_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Qvobjects']))
		{
			$model->attributes=$_POST['Qvobjects'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Qvobjects');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Qvobjects('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Qvobjects']))
			$model->attributes=$_GET['Qvobjects'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Qvobjects::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='qvobjects-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionLoadObjects(){
            if(isset($_POST['Qvobjects']['qvo_docName'])){
                ini_set('soap.wsdl_cache_enabled',0);

                $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
                $client->soap_defentcoding='UTF-8';
                
                $myFields = new GetbeeyeQvObjectList();
                $myFields->_docName=$_POST['Qvobjects']['qvo_docName'];

                $fieldList = $client->GetbeeyeQvObjectList($myFields);               
                
                if(count($fieldList->GetbeeyeQvObjectListResult->beeyeQvObject)>1){
                    foreach($fieldList->GetbeeyeQvObjectListResult->beeyeQvObject as $beeyeQvObjects){
                        $DocName = strtoupper($beeyeQvObjects->DocName);
                        $ObjectName = $beeyeQvObjects->ObjectName;
                        $SheetName = $beeyeQvObjects->SheetName;
                        if(!is_Object(Qvobjects::model()->find('qvo_docName = :docName AND qvo_objectName = :qvo_objectName',array(':docName'=>$DocName,':qvo_objectName'=>$ObjectName)))){
                            $saveField = new Qvobjects();
                            $saveField->qvo_docName = $DocName;
                            $saveField->qvo_objectName = $ObjectName;
                            $saveField->qvo_sheetNumber = $SheetName;
                            $saveField->save();
                        }else{
                            $ActualModel = Qvobjects::model()->find('qvo_docName = :docName AND qvo_objectName = :qvo_objectName',array(':docName'=>$DocName,':qvo_objectName'=>$ObjectName));
                            $ActualModel->qvo_sheetNumber = $SheetName;
                            $ActualModel->save();
                        }
                    }
                }else{
                    $mbReports = $fieldList->GetbeeyeQvObjectListResult->beeyeQvObject;
                    $saveField = new Qvobjects();
                    $saveField->qvo_docName = strtoupper($mbReports->DocName);
                    $saveField->qvo_objectName = $mbReports->ObjectName;
                    $saveField->qvo_sheetNumber = $mbReports->SheetName;
                    $saveField->save();
                }
                
            }
        }
        
        /*
         * @function actionPrintObject() -> returns an image related to the requested url
         */
        
        public function actionPrintObject(){
            
            $MyFilters = 0;
            
            foreach($_GET AS $key=>$value){
                if(substr($key,0,3)=='fff'){
                    $MyFilters = 1;
                    break;
                }
            }
            
            //here i have to check if all relevant parameters are passed
            if(isset($_GET['docName']) AND isset($_GET['objName']) AND isset($_GET['sheetNo'])){    
                // this is the standard connection string to the service
                try {
                    ini_set('soap.wsdl_cache_enabled',1);
                    $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
                    $client->soap_defentcoding='UTF-8';
                    
                    $ObjPrinter = new beeyeQvObject();
                    $ObjPrinter->ObjectID = date("YmdHHmm");
                    $ObjPrinter->DocName = $_GET['docName'];
                    $ObjPrinter->ObjectName = $_GET['objName'];
                    $ObjPrinter->SheetName = $_GET['sheetNo'];
                    $ObjPrinter->RefreshType=1;
                    $ObjPrinter->RefreshFormat="";
                    $ObjPrinter->RefreshDay=0;
                    
                    $ObjRequest = new PrintbeeyeQvObject();
                    $ObjRequest->_docName = $_GET['docName'];
                    $ObjRequest->_objectName = $ObjPrinter;
                    
                    //the filter
                    $Filters=array();
                    if($MyFilters>=1){
                        foreach($_GET AS $key=>$value){
                             if(substr($key,0,3)=='fff'){
                                 $Filters = $this->beeyeDynConditionCleaner($value);
                             }
                        }
                        $ObjRequest->_fieldSelection = $Filters;
                    }else{
                        $ObjRequest->_fieldSelection = "";
                    }
                    
                    $SOAPResponse = $client->PrintbeeyeQvObject($ObjRequest);
                    $bmpURL = $SOAPResponse->PrintbeeyeQvObjectResult;
                    
                    //var_dump($ObjRequest);
                    
                    //echo $bmpURL;
                    //exit;
                    
                    //if all parameters are correct, we will have the image inside the url - be careful that the webserver needs access to the folder, otherwise the following functions would not work
                    //$browserimage = $this->imagecreatefrombmp($bmpURL);
                    
                    header("Content-Type: image/bmp");
                    header("Content-Transfer-Encoding: binary\n");
                    //imagegif($browserimage);
                    //imagedestroy($browserimage);
                    
                    readfile($bmpURL);
                                       
                } catch (Exception $exc) {
                    print_r($exc->getTraceAsString());
                }
                exit;
            }else{
                echo "Missing Parameters:<br/>";
                echo !isset($_GET['docName'])?"docName<br/>":'';
                echo !isset($_GET['objName'])?"objName<br/>":'';
                echo !isset($_GET['sheetNo'])?"sheetNo<br/>":'';                
            }            
        }
        
        private function beeyeConditionCleaner($Condidtion,$FieldName){
            //inititilisieren der filter
            $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
            $newvalues = array();
            if(preg_match("/\,/",$Condidtion)){
                $values = preg_split("/\,/",$Condidtion);
                foreach($values AS $value){
                    if($value != ''){
                        $beeyeQvValue = new beeyeQvValue();
                        $beeyeQvValue->FieldName = $FieldName;
                        $beeyeQvValue->FieldValue = trim($value);                   
                        $newvalues[]=$beeyeQvValue;
                    }
                }
            }else{
                $beeyeQvValue = new beeyeQvValue();
                $beeyeQvValue->FieldName = $FieldName;
                $beeyeQvValue->FieldValue = trim($Condidtion);                   
                $newvalues[]=$beeyeQvValue;
            }
            $Filter = new beeyeQvFieldSelection();
            $Filter->FieldName = $FieldName;
            $Filter->FieldValues=$newvalues;
            return $Filter;
        }
        
        private function beeyeDynConditionCleaner($Condidtion){
            //zerlegen des ausdrucks in die einzelteile
            $filterlines = explode(";",$Condidtion);
            //var_dump($filterlines);
            foreach($filterlines as $filterline){
                if(preg_match("/\=/",$filterline)){
                    $conditions = explode("=",$filterline);
                    //var_dump($conditions);
                    $value = $conditions[1];
                    //inititilisieren der filter
                    $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
                    $newvalues = array();
                    if(preg_match("/\,/",$value)){
                        $values = preg_split("/\,/",$value);
                        foreach($values AS $ffvalue){
                            if($ffvalue != ''){
                                $beeyeQvValue = new beeyeQvValue();
                                $beeyeQvValue->FieldName = $conditions[0];
                                $beeyeQvValue->FieldValue = trim($ffvalue);                   
                                $newvalues[]=$beeyeQvValue;
                            }
                        }
                    }else{
                        $beeyeQvValue = new beeyeQvValue();
                        $beeyeQvValue->FieldName = $conditions[0];
                        $beeyeQvValue->FieldValue = trim($value);                   
                        $newvalues[]=$beeyeQvValue;
                    }

                    $Filters = new beeyeQvFieldSelection();
                    $Filters->FieldName = $conditions[0];
                    $Filters->FieldValues=$newvalues;

                    $Filter[]=$Filters;
                }
            }
                        
            return $Filter;
        }
}
